package com.hspedu.seckill.rabbitmq;

import cn.hutool.json.JSONUtil;
import com.hspedu.seckill.pojo.SeckillMessage;
import com.hspedu.seckill.pojo.User;
import com.hspedu.seckill.pojo.nameMQ;
import com.hspedu.seckill.service.GoodsService;
import com.hspedu.seckill.service.OrderService;
import com.hspedu.seckill.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 消息消费者
 */
@Service
@Slf4j
public class MQReceiverMessage {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private GoodsService goodsService;

    @Autowired
    private OrderService orderService;

    //接收消息，并完成下单
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = nameMQ.QUEUE),
            exchange = @Exchange(name = nameMQ.EXCHANGE,type = ExchangeTypes.TOPIC),
            key = "seckill.#"
    ))
    public void receiveSeckillMessage(String message){

        log.info("接受到的消息是:{}",message);
        SeckillMessage seckillMessage = JSONUtil.toBean(message, SeckillMessage.class);

        User user = seckillMessage.getUser();
        Long goodsId = seckillMessage.getGoodsId();

        //通过商品id找到GoodsVo
        GoodsVo goodsVo = goodsService.findGoodsVoByGoodsId(goodsId);

        //下单
        orderService.seckill(user,goodsVo);
    }
}
